
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PassengerServiceInterface.java
 *
 * Created on 10-May-2012, 12:15:55
 */

/**
 *
 * @author higgina0
 */
public class PassengerServiceInterface extends javax.swing.JFrame {

    private RouteGenerator generator;
    private ArrayList<ArrayList<Bus>> buses;
    /** Creates new form PassengerServiceInterface */
    public PassengerServiceInterface(RouteGenerator generator, 
                                     ArrayList<ArrayList<Bus>> buses)
    {
        this.generator = generator;
        this.buses = buses;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        outputArea = new javax.swing.JTextArea();
        nextServiceButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        hourField = new javax.swing.JFormattedTextField(new java.text.SimpleDateFormat("HH"));
        minuteField = new javax.swing.JFormattedTextField(new java.text.SimpleDateFormat("mm"));
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        dayField = new javax.swing.JFormattedTextField(new java.text.SimpleDateFormat("EEE"));
        stopsList = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Live Updates");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 12));
        jLabel1.setText("Bus Stop: ");

        jLabel2.setFont(new java.awt.Font("DejaVu Sans", 1, 12));
        jLabel2.setText("Time: ");

        outputArea.setColumns(20);
        outputArea.setRows(5);
        outputArea.setDisabledTextColor(new java.awt.Color(1, 1, 1));
        outputArea.setEnabled(false);
        jScrollPane1.setViewportView(outputArea);

        nextServiceButton.setText("Find Next Service");
        nextServiceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextServiceButtonActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("DejaVu Sans", 1, 18));
        jLabel3.setText("Live Updates");

        jLabel4.setFont(new java.awt.Font("DejaVu Sans", 1, 12));
        jLabel4.setText("Output:");

        hourField.setText("HH");

        minuteField.setText("mm");

        jLabel5.setFont(new java.awt.Font("DejaVu Sans", 1, 12));
        jLabel5.setText(":");

        jLabel7.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jLabel7.setText("Day:");

        dayField.setText("day");

        ArrayList<Location> locations = new ArrayList<Location>(this.generator.getLocationsMap().values());
        String[] locationNames = new String[locations.size()];
        for (int i = 0; i< locationNames.length; i++)
        {
            locationNames[i] = locations.get(i).getStopName() + ", " + locations.get(i).getAreaName();
        }
        java.util.Arrays.sort(locationNames);
        System.out.println("Size: " + locationNames.length);
        stopsList.setModel(new javax.swing.DefaultComboBoxModel(locationNames));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(dayField)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(hourField, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(minuteField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(97, 97, 97))
                            .addComponent(nextServiceButton)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(stopsList, 0, 333, Short.MAX_VALUE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(10, 10, 10)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(stopsList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dayField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jLabel2))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(hourField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5)
                                    .addComponent(minuteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(18, 18, 18)
                        .addComponent(nextServiceButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Returns an int value of the day of week,
     * or -1 for failure.
     */
    private int getDayInt()
    {
        String enteredDay = this.dayField.getText();

        if (enteredDay.equalsIgnoreCase("mon"))
            return 0;
        else if(enteredDay.equalsIgnoreCase("tue"))
            return 1;
        else if(enteredDay.equalsIgnoreCase("wed"))
            return 2;
        else if(enteredDay.equalsIgnoreCase("thu"))
            return 3;
        else if(enteredDay.equalsIgnoreCase("fri"))
            return 4;
        else if(enteredDay.equalsIgnoreCase("sat"))
            return 5;
        else if(enteredDay.equalsIgnoreCase("sun"))
            return 6;
        else
            return -1;

    }
    
    private Calendar foundTime = null;
    private Service foundService = null;
    
    private void findNextService()
    {
        String enteredLocation = (String) this.stopsList.getSelectedItem();

        int enteredDay = getDayInt();
        
        if (enteredDay == -1)
        {
            this.outputArea.setText("Error!\nDay does not exist!");
            return;
        }

        int enteredHours;
        int enteredMinutes;

        try
        {
            enteredHours = Integer.parseInt(this.hourField.getText());
            enteredMinutes = Integer.parseInt(this.minuteField.getText());
        }
        catch (NumberFormatException e)
        {
            this.outputArea.setText("Error!\nTime entered is not valid!");
            return;
        }


        ArrayList<Location> locations =
                new ArrayList<Location>(
                    this.generator.getLocationsMap().values());

        Iterator<Location> locationsIter = locations.iterator();
        Location chosenStop = null;
        while (locationsIter.hasNext())
        {
            Location currentLoc = locationsIter.next();
            if (currentLoc.isSameName(enteredLocation))
            {
                chosenStop = currentLoc;
                break;
            }
        }

        if (chosenStop == null)
        {
            this.outputArea.setText("Error!\nStop: " + enteredLocation + " do not exist!");
            return;
        }

        Calendar enteredDate = Calendar.getInstance();
        enteredDate.set(Calendar.DAY_OF_WEEK, enteredDay + 2);
        enteredDate.set(Calendar.HOUR_OF_DAY, enteredHours);
        enteredDate.set(Calendar.MINUTE, enteredMinutes);

        ArrayList<Bus> busesToday = buses.get(enteredDay);
        int bestDuration = 32768;

        //For each bus...
        Iterator<Bus> busIter = busesToday.iterator();
        while (busIter.hasNext())
        {
            //Get its services
            Bus currentBus = busIter.next();
            ArrayList<BusShift> busShifts = currentBus.getShifts();
            //Go through each shift
            Iterator<BusShift> busShiftsIter = busShifts.iterator();
            while (busShiftsIter.hasNext())
            {
                //Get service
                BusShift currentShift = busShiftsIter.next();
                Service currentService = currentShift.getService();
                if (currentService.hasStop(enteredLocation))
                {
                    Calendar time = currentService.getNextTime(enteredDate, enteredLocation);
                    if (time != null)
                    {
                        int minsBetween =  ((time.get(Calendar.HOUR_OF_DAY) * 60) + time.get(Calendar.MINUTE))
                                            - ((enteredDate.get(Calendar.HOUR_OF_DAY) * 60) + enteredDate.get(Calendar.MINUTE));
                                            
                        //System.out.println("Mins between: " + minsBetween);
                        if (minsBetween < bestDuration)
                        {
                            foundService = currentService;
                            foundTime = time;
                            bestDuration = minsBetween;
                        }
                    }
                }
            }
        }
    }


    private void nextServiceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextServiceButtonActionPerformed
        // TODO add your handling code here:

       this.outputArea.setText("");
       String enteredLocation = (String) this.stopsList.getSelectedItem();
       findNextService();
       //Simulate delays and cancellations
       double randomValue = Math.random();

       System.out.println("Found a Service: " +Integer.toString(foundService.getServiceID())
                    + "\nis heading to stop: " + enteredLocation
                    + "\n@" + Service.calendarToString(foundTime));

       //Cancel a service!
       if (randomValue < 0.33)
       {
           System.out.println("Cancelling: " + this.foundService.getServiceID());
           this.foundService.cancel("a horrible accident");
           this.outputArea.setText(this.foundService.getExcuseMessage());
           findNextService();
       }

       else if ((randomValue > 0.33) && (randomValue < 0.66))
       {
            System.out.println("Delaying: " + this.foundService.getServiceID());
           int minutesToDelay = (int) (Math.random() * 50);
           this.foundService.delay(minutesToDelay, " shame");
           this.outputArea.setText(this.foundService.getExcuseMessage());
           findNextService();
       }

        String text = "\nService: " + Integer.toString(foundService.getServiceID())
                    + "\nis heading to stop: " + enteredLocation
                    + "\n@" + Service.calendarToString(foundTime);

        this.outputArea.append(text);
    }//GEN-LAST:event_nextServiceButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        database.openBusDatabase();
        //RouteGenerator gen = new RouteGenerator(Calendar.getInstance());
        //ArrayList<ArrayList<Bus>> buses = gen.getBuses();
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                RouteGenerator gen = new RouteGenerator();
                ArrayList<ArrayList<Bus>> buses = gen.getBuses();
                new PassengerServiceInterface(gen, buses).setVisible(true);
            }
        });
        //database.busDatabase.close();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField dayField;
    private javax.swing.JFormattedTextField hourField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JFormattedTextField minuteField;
    private javax.swing.JButton nextServiceButton;
    private javax.swing.JTextArea outputArea;
    private javax.swing.JComboBox stopsList;
    // End of variables declaration//GEN-END:variables

}
